import { defineStore } from "pinia";
import { Names } from "./store-name";
import { useRequest } from "alova";
import {
  createAdmin,
  deleteAdmin,
  disabledAdmin,
  queryAdminList,
  queryAdminMenu,
} from "../api/admin";
import type {
  TAdminDisableReq,
  TAdminListRes,
  TAdminReq,
} from "@/typing/admin";
import type { TAdminInfo, TAdminMenuInfo } from "@/typing/base";
import type { TResponse } from "../typing/base";
import { arrayToTreeNodes, expendAll, treeSelecedKeys } from "@/utils/util";
import type { TreeSelectionKeys } from "primevue/tree";
import { editAdminMenu } from '../api/admin';

export const useAdminStore = defineStore(Names.ADMIN, {
  state: () => {
    return {
      adminList: <TAdminInfo[]>[],
      isLoading: false,
      adminMenuList: <TAdminMenuInfo[]>[],
    };
  },
  getters: {
    getLoading(state): boolean {
      return state.isLoading;
    },
    getNodes(state) {
      const nodes = arrayToTreeNodes(state.adminMenuList);
      const expandedKeys: any = expendAll(nodes)
      return {
        nodes,
        expandedKeys
      };
    },
    getSelectKeys(state) {
      const nodes = arrayToTreeNodes(state.adminMenuList);
      const selectedKeys: TreeSelectionKeys = treeSelecedKeys(nodes)
      console.log('selectedKeys', selectedKeys)
      return selectedKeys
    }
  },

  actions: {
    queryAdminList({ force }: { force?: boolean } = { force: false }) {
      const { onSuccess } = useRequest(queryAdminList(), { force: force });
      onSuccess(({ data }: { data: TAdminListRes }) => {
        this.adminList = data.data.adminList;
      });
    },
    createAdmin(req: TAdminReq, fn: Function) {
      const { onSuccess } = useRequest(createAdmin(req));
      onSuccess((res) => {
        fn && fn(res.data);
      });
    },
    disabledAdmin(req: TAdminDisableReq, fn: Function) {
      const { onSuccess } = useRequest(disabledAdmin(req));
      onSuccess((res) => {
        if (res.data) {
          fn && fn(res.data);
        }
      });
    },
    deleteAdmin(req: Pick<TAdminDisableReq, "id">, fn: Function) {
      const { onSuccess } = useRequest(deleteAdmin(req));
      onSuccess((res) => {
        if (res.data) {
          fn && fn(res.data);
        }
      });
    },
    queryAdminMenu(id: string, fn: Function) {
      this.$patch((state) => {
        state.isLoading = true;
      });
      const { onSuccess } = useRequest(queryAdminMenu(id));
      onSuccess((res) => {
        if (res.data) {
          const {
            data: { adminMenuList },
          } = res.data as TResponse<{ adminMenuList: TAdminMenuInfo[] }>;
          this.adminMenuList = adminMenuList;
          this.isLoading = false;
          fn && fn(res.data);
        }
      });
    },
    editAdminMenu(req: Record<'id' & 'actions', string>, fn: Function) {
      const { onSuccess } = useRequest(editAdminMenu(req));
      onSuccess((res) => {
        if (res.data) {
          fn && fn(res.data);
        }
      });
    },
  },
});
